package net.maku.kyy.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import net.maku.framework.common.exception.ErrorCode;
import net.maku.framework.common.exception.ServerException;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.framework.security.cache.TokenStoreCache;
import net.maku.framework.security.properties.SecurityProperties;
import net.maku.framework.security.user.UserDetail;
import net.maku.framework.security.utils.TokenUtils;
import net.maku.kyy.convert.KyyUserConvert;
import net.maku.kyy.convert.KyyUserTokenConvert;
import net.maku.kyy.dao.KyyUserDao;
import net.maku.kyy.entity.KyyUserEntity;
import net.maku.kyy.entity.KyyUserTokenEntity;
import net.maku.kyy.service.KyyUserDetailsService;
import net.maku.kyy.vo.KyyUserTokenVO;
import net.maku.kyy.dao.KyyUserTokenDao;
import net.maku.kyy.service.KyyUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 应用用户token表
 *
 * @author MAKU babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
@AllArgsConstructor
public class KyyUserTokenServiceImpl extends BaseServiceImpl<KyyUserTokenDao, KyyUserTokenEntity> implements KyyUserTokenService {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private TokenStoreCache tokenStoreCache;

    @Autowired
    private KyyUserDao kyyUserDao;

//    @Autowired
//    private KyyUserDetailsService kyyUserDetailsService;

    /**
     * 创建token
     * @param userId 用户ID
     * @return
     */
    @Override
    public KyyUserTokenVO createToken(Long userId) {
        // 生成token
        String accessToken = TokenUtils.generator();
        String refreshToken = TokenUtils.generator();
        KyyUserTokenEntity kyyUserTokenEntity = new KyyUserTokenEntity().builder()
                .userId(userId)
                .accessToken(accessToken)
                .build();
        // 过期时间
        Date now = new Date();
        kyyUserTokenEntity.setAccessTokenExpire(DateUtil.toLocalDateTime(DateUtil.offsetSecond(now, securityProperties.getAccessTokenExpire())));
        kyyUserTokenEntity.setRefreshTokenExpire(DateUtil.toLocalDateTime(DateUtil.offsetSecond(now, securityProperties.getRefreshTokenExpire())));
        //该用户是否存在token
        KyyUserTokenEntity tokenEntity = baseMapper.selectOne(new LambdaQueryWrapper<KyyUserTokenEntity>().eq(KyyUserTokenEntity::getUserId, userId));
        if (tokenEntity == null) {
            // 用户不存在token，则给用户插入token
            baseMapper.insert(kyyUserTokenEntity);
        } else {
            // 存在token，则更新
            kyyUserTokenEntity.setId(tokenEntity.getId());
        }
        //返回
        return KyyUserTokenConvert.INSTANCE.convert(kyyUserTokenEntity);
    }

    /**
     * 刷新token
     * @param refreshToken refreshToken
     * @return
     */
    @Override
    public KyyUserTokenVO refreshToken(String refreshToken) {
        LambdaQueryWrapper<KyyUserTokenEntity> query = Wrappers.lambdaQuery();
        query.eq(KyyUserTokenEntity::getRefreshToken, refreshToken);
        query.ge(KyyUserTokenEntity::getRefreshTokenExpire, new Date());
        // 不存在，则表示refreshToken错误，或者已过期
        KyyUserTokenEntity entity = baseMapper.selectOne(query);
        if (entity == null) {
            throw new ServerException(ErrorCode.REFRESH_TOKEN_INVALID);
        }
        //删除缓存信息
        tokenStoreCache.deleteUser(entity.getAccessToken());
        //生成新 accessToken
        String accessToken = TokenUtils.generator();
        entity.setAccessToken(accessToken);
        entity.setAccessTokenExpire(DateUtil.toLocalDateTime(DateUtil.offsetSecond(new Date(), securityProperties.getAccessTokenExpire())));

        // 更新
        baseMapper.updateById(entity);

        // 设置用户权限信息
        KyyUserEntity user = kyyUserDao.selectById(entity.getUserId());
        UserDetail userDetail = KyyUserConvert.INSTANCE.convertDetail(user);
//        kyyUserDetailsService.getUserDetails(userDetail);

        // 保存用户信息到缓存
        tokenStoreCache.saveUser(accessToken, userDetail);

        return KyyUserTokenConvert.INSTANCE.convert(entity);
    }

    /**
     * 删除token 退出登录
     * @param userId 用户ID
     */
    @Override
    public void expireToken(Long userId) {
        KyyUserTokenEntity entity = new KyyUserTokenEntity();
        LocalDateTime now = LocalDateTime.now();
        entity.setAccessTokenExpire(now);
        entity.setRefreshTokenExpire(now);
        baseMapper.update(entity, new LambdaQueryWrapper<KyyUserTokenEntity>().eq(KyyUserTokenEntity::getUserId, userId));
    }

    /**
     * 根据角色ID，更新Cache里面的用户权限
     * @param roleId 角色ID
     */
    @Override
    public void updateCacheAuthByRoleId(Long roleId) {
        // 根据角色ID，查询用户 access_token 列表
//        List<String> accessTokenList = baseMapper.getOnlineAccessTokenListByRoleId(roleId, LocalDateTime.now());
//
//        accessTokenList.forEach(this::uopdateCacheAuth);
    }

    /**
     * 根据accessToken，更新Cache里面的用户权限
     * @param userId 用户ID
     */
    @Override
    public void updateCacheAuthByUserId(Long userId) {

    }
}